package tongcheng.com.tongcheng.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.RequestMethod;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import tongcheng.com.tongcheng.ConStans;
import tongcheng.com.tongcheng.R;
import tongcheng.com.tongcheng.adapter.ShigongAdapter;
import tongcheng.com.tongcheng.bean.StatusBean;
import tongcheng.com.tongcheng.bean.UpImageBean;
import tongcheng.com.tongcheng.network.CallServer;
import tongcheng.com.tongcheng.network.MyRequest;
import tongcheng.com.tongcheng.network.OnCallBack;
import tongcheng.com.tongcheng.utils.GsonUtil;
import tongcheng.com.tongcheng.utils.Setting;
import tongcheng.com.tongcheng.utils.ShowToast;
import tongcheng.com.tongcheng.widght.MessageDialog;
import tongcheng.com.tongcheng.zhifubao.PayResult;

import static tongcheng.com.tongcheng.base.AllOrderDetialActivity.xiangInstance;

public class FinishShigongActivity extends BaseActivity {


    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.back_text)
    TextView mBackText;
    @Bind(R.id.title)
    TextView mTitle;
    @Bind(R.id.title_bar)
    RelativeLayout mBg;
    @Bind(R.id.shigong_rc)
    RecyclerView mShigongRc;
    @Bind(R.id.shigong_ll1)
    LinearLayout mShigongLl1;
    @Bind(R.id.shigong_ll2)
    LinearLayout mShigongLl2;
    @Bind(R.id.shigong_ll3)
    LinearLayout mShigongLl3;
    @Bind(R.id.shigong_ok)
    Button mShigongOk;
    @Bind(R.id.title_line)
    View mTitleLine;
    @Bind(R.id.shigong_ratingleft)
    RatingBar mShigongRatingleft;
    @Bind(R.id.shigong_ratingright)
    RatingBar mShigongRatingright;
    @Bind(R.id.shigong_pingjia)
    EditText mShigongPingjia;
    @Bind(R.id.rb_weiXinFuKuan)
    RadioButton rb_weiXinFuKuan;
    @Bind(R.id.rb_zhiFuBaoFuKuan)
    RadioButton rb_zhiFuBaoFuKuan;
    @Bind(R.id.rb_yu_eFuKuan)
    RadioButton rb_yu_eFuKuan;
    @Bind(R.id.tv_money)
    TextView tv_money;


    private String mWork_end_pic;
    private int mId;
    private int mType;
    private ShigongAdapter mSendOrderAdapter;
    private List<LocalMedia> selectList;
    private List<String> filepath = new ArrayList<>();
    private StringBuffer mSb;
    private String mScene_pic = "";
    private String order_no = "";
    private String price = "";
    private MessageDialog mMessageDialog;
    private int temp = 0;
    int tt = 0;
    @Override
    public Integer initResid() {
        return R.layout.activity_finish_shigong;
    }

    @Override
    public void initCreate(Bundle savedInstanceState) {
        mMessageDialog = new MessageDialog(this);
        mMessageDialog.setOkClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMessageDialog.dismiss();
                if(tt == 1){
                    if(xiangInstance != null){
                        xiangInstance.finish();
                    }
                }
                finish();
            }
        });
        mType = getIntent().getIntExtra("type", -1);
        mId = getIntent().getIntExtra("id", -1);
        order_no = getIntent().getStringExtra("order_no");
        price = getIntent().getStringExtra("price");
//        DecimalFormat sdf = new DecimalFormat("#0.00");
//        String text = sdf.format(price);
//        tv_money.setText(text);
        tv_money.setText(price + "");
        mWork_end_pic = getIntent().getStringExtra("work_end_pic");
        mTitle.setText("完成施工");
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mShigongRc.setLayoutManager(gridLayoutManager);
        mSendOrderAdapter = new ShigongAdapter(filepath, this, this, mBg);
        mShigongRc.setAdapter(mSendOrderAdapter);


        //微信支付
        rb_weiXinFuKuan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    temp = 1;
                    rb_zhiFuBaoFuKuan.setChecked(false);
                    rb_yu_eFuKuan.setChecked(false);
                }
            }
        });

        //支付宝支付
        rb_zhiFuBaoFuKuan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    temp = 2;
                    rb_weiXinFuKuan.setChecked(false);
                    rb_yu_eFuKuan.setChecked(false);
                }

            }
        });

        //余额支付
        rb_yu_eFuKuan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    temp = 3;
                    rb_weiXinFuKuan.setChecked(false);
                    rb_zhiFuBaoFuKuan.setChecked(false);
                }

            }
        });

        //确认支付
        mShigongOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(mSb == null){
                    ShowToast.showToast("订单完成后现场图片不能为空");
                }else if(TextUtils.isEmpty(mShigongRatingright.getRating() + "")){
                    ShowToast.showToast("综合星级评分不能为空");
                }else if(TextUtils.isEmpty(mShigongRatingleft.getRating() + "")){
                    ShowToast.showToast("施工质量评分不能为空");
                }else if(TextUtils.isEmpty(mShigongPingjia.getText().toString().trim())){
                    ShowToast.showToast("评价内容不能为空");
                }else {
                    if(temp == 1){//微信

                    }else if(temp == 2){//支付宝
                        Log.e("星级",mShigongRatingright.getRating() + "---" + mShigongRatingleft.getRating());
                        zhiFuBao();
                    }else if(temp == 3){//余额

                    }else {
                        ShowToast.showToast("请选择一种支付方式");
                    }
                }

//                FinishShigong();

            }
        });

        filepath.clear();
    }

    private void zhiFuBao() {
        MyRequest myRequest = new MyRequest(ConStans.ZhiFuUrl, RequestMethod.POST);
        myRequest.add("userid", Setting.getId());
        myRequest.add("total_amount",price );
        myRequest.add("type",2);
        myRequest.add("out_trade_no",order_no);
        CallServer.getInstance().addPost(FinishShigongActivity.this, myRequest, 3, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {

                try {
                    Log.e("支付宝参数",json);
                    JSONObject object = new JSONObject(json);
                    if(object.getInt("status") == 1){
                        String text = object.getString("data");
                        alipay(text);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //完成施工
    private void FinishShigong() {
        if (mSb != null) {
            mScene_pic = mSb.toString();
        }

        MyRequest request = new MyRequest(ConStans.OrderDetialButton_Url, RequestMethod.POST);
        request.add("type", 5);
        request.add("id", mId);
        request.add("work_end_pic", mScene_pic);
        request.add("total", mShigongRatingright.getRating() + "");
        request.add("quality", mShigongRatingleft.getRating() + "");
        request.add("comment", mShigongPingjia.getText().toString().trim());
        Log.e("星级",mShigongRatingright.getRating() + "---" + mShigongRatingleft.getRating());
        CallServer.getInstance().addPost(this,request, 1, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                StatusBean statusBean = GsonUtil.GsonToBean(json, StatusBean.class);
                if (statusBean != null) {
                    if (statusBean.status == 1) {
                        tt = 1;
                        mMessageDialog.setTitle("提交成功").setMessage("请移至订单中心查看订单进度").setIcon(R.mipmap.tijiao).showit();

//                        Intent mIntent = new Intent(FinishShigongActivity.this, MainActivity.class);
//                        mIntent.putExtra("bool",true);
//                        startActivity(mIntent);
//                        if(xiangInstance != null){
//                            xiangInstance.finish();
//                        }
//                        finish();

                    } else {
                        mMessageDialog.setTitle("提交失败").setMessage(statusBean.msg+"").setIcon(R.mipmap.quxiao).showit();
                    }
                }
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // ShowToast.showToast("我被回调了");
//                    for (LocalMedia localMedia : selectList) {
//                        Log.e("tag", localMedia.getPath());
//                        filepath.add(localMedia.getPath());
//                        mSendOrderAdapter.notifyDataSetChanged();
//                    }

                    UpImage(selectList);

                    break;
            }
        }
    }


    //上传图片
    private void UpImage(List<LocalMedia> selectList) {
        MyRequest request = new MyRequest(ConStans.UpImage_Url, RequestMethod.POST);
        request.add("code", "image");
        request.add("num", selectList.size());
        Log.e("size", selectList.size() + "");
        for (int i = 0; i < selectList.size(); i++) {
            boolean bb = selectList.get(i).isCompressed();
            if(bb){
                request.add("image" + (i + 1), new FileBinary(new File(selectList.get(i).getCompressPath())));
            }else {
                request.add("image" + (i + 1), new FileBinary(new File(selectList.get(i).getPath())));
            }

        }
        mSb = new StringBuffer();
        // request.add("picture", new FileBinary(new File(selectList.get(0).getPath())));
        CallServer.getInstance().addPost(this,request, 1, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                Log.e("上传图片",json + "");
                UpImageBean upImageBean = GsonUtil.GsonToBean(json, UpImageBean.class);
                if (upImageBean != null) {
                    List<UpImageBean.DataBean> data = upImageBean.data;
                    if (data != null) {
                        for (int i = 0; i < data.size(); i++) {
                            Log.e("上传图片11",ConStans.BaseUrl_Test_url + data.get(i).filename + "");
                            filepath.add(ConStans.BaseUrl_Test_url + data.get(i).filename);
                            mSb.append(data.get(i).filename + ",");
                        }
                        mSendOrderAdapter.notifyDataSetChanged();

                    }
                }
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    //去支付宝支付
    public void alipay(final String data) {

        // 完整的符合支付宝参数规范的订单信息

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(FinishShigongActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(data);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {

                        Toast.makeText(FinishShigongActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

                        //完成施工
                        FinishShigong();

                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(FinishShigongActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(FinishShigongActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(FinishShigongActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    };


}
